//
//  ItemDetailViewController.swift
//  Checklists
//
//  Created by wyatt on 15/3/7.
//  Copyright (c) 2015年 Razeware. All rights reserved.
//

import UIKit


// Step 1: 定义一个代理协议
protocol ItemDetailViewControllerDelegage: class {
    func itemDetailViewControllerDidCancel(controller: ItemDetailViewController)
    func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: ChecklistItem)
    func addItemviewController(controller: ItemDetailViewController, didFinishEditingItem item: ChecklistItem)
}

class ItemDetailViewController: UITableViewController, UITextFieldDelegate {
    
    // Step 2: 定义一个代理类型的变量，相当于一个发声开关。
    weak var delegate: ItemDetailViewControllerDelegage?
    
    var itemToEdit: ChecklistItem? // 用于存储被修改的数据项内容。
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = 44
        
        // 读取itemToEdit，判断是否有值，有值的话，则修改title及TextField的内容
        if let item = itemToEdit {
            title = "Edit Item"
            textField.text = item.text
            doneBarButton.enabled = true
        }
    }
    
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    
    // 将输入光标定位到text field框中
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        textField.becomeFirstResponder()
    }
    
    @IBOutlet weak var textField: UITextField!
    
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        return nil
    }
    
    // Step 3: 需要向A发送信息时，则开始使用发声装置
    @IBAction func cancel() {
        delegate?.itemDetailViewControllerDidCancel(self)
//        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @IBAction func done() {
        if let item = itemToEdit {
            item.text = textField.text
            delegate?.addItemviewController(self, didFinishEditingItem: item)
        } else {
            let item = ChecklistItem()
            item.text=textField.text
            item.checked = false
            // 传值
            delegate?.itemDetailViewController(self, didFinishAddingItem: item)
        }

    }
    
    // 根据文本框中的内容，来确定Done的是否可用
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let oldText: NSString = textField.text
        let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
        
        doneBarButton.enabled = (newText.length > 0)
        
        return true
    }

}
